package com.dhgate.amazonCraw.redis;

import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 配置redis连接
 * @author lidongyang
 * @createtime Jan 16, 2013 10:30:02 AM
 */
public class RedisConifg {
	
	/**
	 * 标志配置文件是否已经初始化 默认：否
	 */
	private static boolean isInited = false;
	
	/**
	 * redis资源文件
	 */
	private static Properties redis_properties = new Properties();
	
	/**
	 * redis相关参数
	 */
	private static RedisParam redisParam = null;
	
	
	/**
	 * 获取redis的相关参数
	 * @return
	 */
	public static RedisParam getRedisParam() {
		if(!isInited) {
			init();
		}
		return redisParam;
	}
	
	/**
	 * 初始化配置文件
	 */
	public static void init() {
		loadRedisSettingFile("redis");
		
		initRedisConfig();
		
		isInited = true;
	}
	
	/**
	 * 加载Redis的资源文件
	 * @param resourceName
	 */
	private static synchronized void loadRedisSettingFile(String resourceName) {
		Properties properties = redis_properties;
		ResourceBundle oResourceBundle = ResourceBundle.getBundle(resourceName);
		Enumeration oEnumeration = oResourceBundle.getKeys();

		String oKey = null, oValue = null;
		while (oEnumeration.hasMoreElements()) {
			oKey = (String) oEnumeration.nextElement();
			oValue = oResourceBundle.getString(oKey);
			properties.put(oKey, oValue);
		}
	}
	
	/**
	 * 初始化Redis的资源配置
	 */
	private static void initRedisConfig() {
		redisParam = new RedisParam();
		redisParam.setServerIp(getRedisProperty("redis.ip"));
		redisParam.setServerPort(getRedisProperty("redis.port"));
		redisParam.setMaxActive(getRedisProperty("redis.pool.maxActive"));
		redisParam.setMaxIdle(getRedisProperty("redis.pool.maxIdle"));
		redisParam.setMaxWait(getRedisProperty("redis.pool.maxWait"));
		redisParam.setTestOnBorrow(getRedisProperty("redis.pool.testOnBorrow"));
		redisParam.setTestOnReturn(getRedisProperty("redis.pool.testOnReturn"));
	}
	
	/**
	 * 获取redis的资源文件key值
	 * @param key
	 * @return
	 */
	private static String getRedisProperty(String key) {
		return getProperty(key, "redis");
	}
	
	/**
	 * 获取资源文件key值
	 * 
	 * @param key key
	 * @param type 类型（redis、DB、系统配置）
	 * @return key值
	 */
	private static String getProperty(String key, String type) {
		Properties properties = null;
		if ("redis".equals(type)) {
			properties = redis_properties;
		}
		return properties.getProperty(key);
	}
	
}
